﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using Microsoft.Win32;
using Spinka.Properties;
using SaviorClass;

namespace Spinka
{
    public partial class Spinka : Form
    {
        const string spinaczUrl = "http://spinacz.pl/";
        private long LastId = 0;
        private long LastCommentId = 0;
        private int interval = 0;
        private HttpWebResponse resp;
        private string openUrl = "";
        private Boolean canClose = false;
        private Settings Settings;
        private string spinaczRegister = "http://spinacz.pl/register";
        private string SpinkaRegeditPath = "Software\\Spinka\\Settings";

        public Spinka()
        {
            InitializeComponent();
        }

        private void zakończToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.canClose = true;
            this.SaveSettings();
            Application.Exit();
        }

        private void removeAutoStart()
        {
            RegistryKey masterKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
            string regValue = masterKey.GetValue("Spinka", "").ToString();
            if (regValue != "")
            {
                masterKey.DeleteValue("Spinka");
            }
            masterKey.Close();
        }

        private void setAutoStart()
        {
            RegistryKey masterKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
            string regValue = masterKey.GetValue("Spinka","").ToString();
            if (regValue == "")
            {
                masterKey.SetValue("Spinka", "\""+Application.ExecutablePath.ToString()+"\"");
                Console.WriteLine("Zapisalem klucz");
            }
            masterKey.Close();
        }

        private void countInterval()
        {
            switch (Settings.Interval)
            {
                case 0:
                    this.interval = 0;
                    break;
                case 1:
                    this.interval = 1000 * 60;
                    break;
                case 2:
                    this.interval = 2000 * 60;
                    break;
                case 3:
                    this.interval = 5000 * 60;
                    break;
                case 4:
                    this.interval = 10000 * 60;
                    break;
                default:
                    this.interval = 0;
                    break;
            }
        }

        private void SaveSettings()
        {
            this.Settings.LastId = this.LastId.ToString();
            this.Settings.LastCommentId = this.LastCommentId.ToString();
            // Jezeli zmieniles login to zresetuj LastId
            if (this.loginBox.Text != this.Settings.Login)
            {
                this.Settings.LastId = "0";
            }
            this.Settings.Login = this.loginBox.Text;
            this.Settings.AutoRun = this.autoRun.Checked;
            this.Settings.Interval = this.intervalBox.SelectedIndex;
            Savior.Save(this.Settings, this.SpinkaRegeditPath);

            this.countInterval();
            if (this.Settings.AutoRun == true)
            {
                setAutoStart();
            }
            else
            {
                removeAutoStart();
            }

        }

        private void ustawieniaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                e.SuppressKeyPress = true;
            }
        }

        private void Spinka_Load(object sender, EventArgs e)
        {
            // Zaladuj ustawienia
            this.Settings = new Settings();
            Savior.Read(this.Settings, this.SpinkaRegeditPath);

            this.loginBox.Text = this.Settings.Login;
            this.autoRun.Checked = this.Settings.AutoRun;
            notifyIcon1.Text = "Spinka";
            
            this.LastId = Int64.Parse(this.Settings.LastId);
            this.LastCommentId = Int64.Parse(this.Settings.LastCommentId);

            this.intervalBox.SelectedIndex = this.Settings.Interval;
            this.countInterval();
            if (this.Settings.Login.Length == 0)
            {
                Show();
                WindowState = FormWindowState.Normal;
            }
            else
            {
                this.setAndRunTimer();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            this.setAndRunTimer();
            Hide();
            WindowState = FormWindowState.Minimized;
        }

        private void enableAnimation()
        {
            notifyIcon1.Icon = getSpinkaIcon(0);
        }

        private void disableAnimation()
        {
            notifyIcon1.Icon = getSpinkaIcon(1);
        }

        private void setAndRunTimer()
        {
            chkTimer.Stop();
            if (Settings.Interval > 0)
            {
                Console.WriteLine("Uruchamiam timer: " + this.interval.ToString());
                chkTimer.Interval = this.interval;
                chkTimer.Start();
            }
        }

        private bool GetComments()
        {
            string url = "http://spinacz.pl/comments/getpage.xml?login=" + Settings.Login;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "GET";
            req.Referer = url;
            req.UserAgent = "Spinka .NET Application";
            try
            {
                this.resp = (HttpWebResponse)req.GetResponse();
            }
            catch (Exception e)
            {
                this.showBalloon("Uppss.. wystąpił błąd :(", e.Message.ToString());
                return false;
            }
            System.IO.StreamReader sr = new System.IO.StreamReader(this.resp.GetResponseStream());
            string result = sr.ReadToEnd().Trim();

            if (result.Length == 0)
            {
                this.showBalloon("Uppss.. wystąpił błąd", "Brak odpowiedzi z serwera. Sprawdź czy jesteś podłączony do internetu.");
                return false;
            }

            XmlDocument doc;
            XmlElement root;
            XmlNodeList spinacz;

            try
            {
                doc = new XmlDocument();
                doc.InnerXml = result;
                root = doc.DocumentElement;
                spinacz = root.SelectNodes("/spinacz/entry");
            }
            catch (Exception e)
            {
                this.showBalloon("Uppss.. wystąpił błąd", "Upewnij się, że wpisany login jest poprawny.");
                this.openUrl = "SHOWSETTING";
                Console.WriteLine(e.Message.ToString());
                return false;
            }

            Console.WriteLine("LastCommentId: " + this.LastCommentId.ToString());
            Komentarz msg = new Komentarz();
            msg.setLastId(this.LastCommentId);
            msg.setLogin(Settings.Login.ToString());
            msg.setKomentarze(spinacz);
            string[] m = msg.getKomentarz();

            if (m[0] != "")
            {
                this.openUrl = m[2];
                this.showBalloon(m[0], m[1]);
            }
            this.LastCommentId = Convert.ToInt64(m[3]);
            return true;
        }


        private bool GetFeeds(bool showInfoOnEmpty)
        {
            this.enableAnimation();
            notifyIcon1.Text = "Spinka - Sprawdzam nowe wpisy...";

            Console.WriteLine("Spradzam wpisy...");

            if (Settings.Login.Length == 0)
            {
                Console.WriteLine("Brak ustawionego loginu. Kończe pobieranie.");
                this.disableAnimation();
                return false;
            }
            string url = "http://spinacz.pl/feeds/getboard.xml?login="+Settings.Login;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "GET";
            req.Referer = url;
            req.UserAgent = "Spinka .NET Application";
            try
            {
                this.resp = (HttpWebResponse)req.GetResponse();
            }
            catch (Exception e)
            {
                this.showBalloon("Uppss.. wystąpił błąd :(", e.Message.ToString());
                return false;
            }
 
            System.IO.StreamReader sr = new System.IO.StreamReader(this.resp.GetResponseStream());
            string result = sr.ReadToEnd().Trim();

            if (result.Length == 0)
            {
                this.showBalloon("Uppss.. wystąpił błąd", "Brak odpowiedzi z serwera. Sprawdź czy jesteś podłączony do internetu.");
                return false;
            }
            
            XmlDocument doc;
            XmlElement root;
            XmlNodeList error;

            try
            {
                doc = new XmlDocument();
                doc.InnerXml = result;
                root = doc.DocumentElement;
                error = root.SelectNodes("/spinacz/status");
            }
            catch (Exception e)
            {
                this.showBalloon("Uppss.. wystąpił błąd", "Upewnij się, że wpisany login jest poprawny.");
                this.openUrl = "SHOWSETTING";
                Console.WriteLine(e.Message.ToString());
                return false;
            }

            if (error.Count > 0 && error.Item(0).InnerText == "error") 
            {
                this.showBalloon("Uppss.. wystąpił błąd", "Upewnij się, że wpisany login jest poprawny.");
                this.openUrl = "SHOWSETTING";
                return false;
            }

            XmlNodeList spinacz = root.SelectNodes("/spinacz/entry");

            Wiadomosc msg = new Wiadomosc();
            msg.setLastId(this.LastId);
            msg.setLogin(Settings.Login.ToString());
            msg.setWiadomosci(spinacz);
            
            string [] m = msg.getWiadomosc();
            if ((showInfoOnEmpty == true && m[0] == msg.DefaultNoneHeader) || m[0] != msg.DefaultNoneHeader)
            {
                this.openUrl = m[2];
                this.showBalloon(m[0], m[1]);
            }
            this.LastId = Convert.ToInt64(m[3]);


            // Tutaj pobierz komentarze
            if (m[0] == msg.DefaultNoneHeader)
            {
                this.GetComments();
            }


            this.disableAnimation();
            notifyIcon1.Text = "Spinka";
            this.SaveSettings();
            return true;
        }

        private void sprawdźTerazToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool result = this.GetFeeds(true);
        }

        private void showBalloon(string Title, string Message)
        {
            if (Title.Length > 0 && Message.Length > 0)
            {
                notifyIcon1.ShowBalloonTip(30, Title, Message, ToolTipIcon.Info);
            }
            notifyIcon1.Text = "Spinka";
            this.disableAnimation();
            this.SaveSettings();
        }

        private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
        {
            Console.WriteLine("Otwieram " + this.openUrl.ToString());
            if (this.openUrl == "SHOWSETTING")
            {
                this.openUrl = "";
                Show();
                WindowState = FormWindowState.Normal;
            } else if(this.openUrl.Length > 0) {
                try
                {
                    System.Diagnostics.Process.Start(this.openUrl);
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message.ToString());
                }
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            bool result = this.GetFeeds(true);
        }

        private void chkTimer_Tick(object sender, EventArgs e)
        {
            bool result = this.GetFeeds(false);
        }

        private void Spinka_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.SaveSettings();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Hide();
        }

        private void Spinka_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.canClose == false)
            {
                e.Cancel = true;
                Hide();
            }
            
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(this.spinaczRegister);
        }

        private Icon getSpinkaIcon(decimal i)
        {
            if (i == 0)
            {
                return new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Spinka.spinacz-pl.2.ico"));
             
            }
            else
            {
                return new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Spinka.spinacz-pl.1.ico"));
            }
        }
    }

    [Serializable]
    public class Settings
    {
        public String Login = "";
        public int Interval = 1;
        public Boolean AutoRun = true;
        public String LastId = "0";
        public String LastCommentId = "0";
    }
}
